<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="title" :visible="showDialog" @close="cancelBtn">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model.trim="formData.manager" style="width:80%" placeholder="请选择" @blur="checkManagerRepeat">
          <el-option
            v-for="user in employees"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model.trim="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnFn">确定</el-button>
        <el-button size="small" @click="cancelBtn">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { addDepartments, DepartmentDetails, editDepartments, getDepartments } from '@/api/departments'
import { getEmployees } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    nodeDate: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkNameRepeat = (rule, value, callback) => {
      // 方法一

      let isRepeat
      if (this.formData.id) {
        isRepeat = this.depts
          .filter(item => item.pid === this.nodeDate.pid)
          .some(item => item.name === value && item.id !== this.formData.id)
      } else {
        isRepeat = this.depts
          .filter(item => item.pid === this.nodeDate.id)
          .some(item => item.name === value)
      }

      // 判断
      if (isRepeat) {
        // 失败
        callback(new Error('该部门有此部门了'))
      } else {
        callback()
      }
      // 方法二
      // const arrRpeat = []
      // this.depts.forEach(item => {
      //   if (item.pid === this.nodeDate.id) {
      //     arrRpeat.push(item)
      //   }
      // })
      // arrRpeat.some(item => item.name === value) ? callback(new Error('该部门有这个名字')) : callback()
      // // console.log(arrRpeat)
    }
    const checkCodeRepeat = (rule, value, callback) => {
      let isCode
      if (this.formData.id) {
        isCode = this.depts.some(item => item.code === value && item.id !== this.formData.id)
      } else {
        isCode = this.depts.some(item => item.code === value)
      }

      isCode ? callback(new Error('编码不能重复')) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        introduce: '',
        pid: '',
        manager: ''
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '不能为空' },
          { max: 50, message: '长度必须小于50', tigger: 'blur' },
          { tigger: 'bulr', validator: checkNameRepeat }
        ],
        code: [
          { required: true, trigger: 'blur', message: '不能为空' },
          { max: 50, message: '长度必须小于50', tigger: 'blur' },
          { tigger: 'blur', validator: checkCodeRepeat }
        ],
        manager: [
          { tigger: 'blur', message: '不能为空', required: true }
        ],
        introduce: [
          { required: true, trigger: 'blur', message: '不能为空' },
          { max: 300, message: '长度必须小于300' }
        ]
      },
      depts: [],
      employees: []

    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }

  },
  async created() {
    this.getDepartments()
    // 获取员工简单信息列表
    this.getEmployees()
  },
  methods: {
    // 获取所有部门列表
    async getDepartments() {
      const { depts } = await getDepartments()
      this.depts = depts
      // console.log(this.depts)
    },
    // 获取员工简单信息列表
    async  getEmployees() {
      this.employees = await getEmployees()
    },
    // 选择器失去焦点时触发
    checkManagerRepeat() {
      this.$refs.addDept.validateField('manager')
    },
    // 点击确认按钮
    async btnFn() {
      // 校验表单
      await this.$refs.addDept.validate()
      // 发送请求
      // 根据formData有没有ID判断是编辑还是新增
      if (this.formData.id) {
        await editDepartments(this.formData)
      } else {
        await addDepartments({
          ...this.formData,
          pid: this.nodeDate.id
        })
      }
      // 提示用户
      this.$message.success('添加成功')
      // 关闭弹窗
      this.$emit('update:showDialog', false)
      // 数据跟新
      this.$emit('getDepartments')
      // 弹窗页也要跟新数据
      this.getDepartments()
    },
    // 点击取消按钮
    cancelBtn() {
      this.formData = {
        name: '',
        code: '',
        introduce: '',
        pid: '',
        manager: ''
      }
      this.$refs.addDept.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 查询部门详情
    async DepartmentDetails(id) {
      this.formData = await DepartmentDetails(id)
      console.log(this.formData)
    }
  }
}
</script>

<style>

</style>
